package jjn.round1;

import java.util.TreeMap;

/**
 * @author Jjn
 * @since 2022-10-08 14:38
 */
public class LeetCode870_AdvantageShuffle {
    public int[] advantageCount(int[] nums1, int[] nums2) {
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int j : nums1) {
            Integer count = map.getOrDefault(j, 0);
            map.put(j, ++count);
        }
        int[] result = new int[nums1.length];
        for (int i = 0; i < nums2.length; i++) {
            Integer threshold = map.ceilingKey(nums2[i] + 1);
            if (threshold == null) {
                threshold = map.ceilingKey(-1);
            }
            result[i] = threshold;
            Integer count = map.get(threshold);
            count--;
            if (count > 0) {
                map.put(threshold, count);
            } else {
                map.remove(threshold);
            }
        }
        return result;
    }
    
}
